const express = require('express')
const router = express.Router()
const pool = require('../pool')
const query = require('./utils');
const request = require('request')
const multer = require('multer');
const upload = multer({
    dest: 'image/userInfo/'
})
const axios = require('axios');

const {host} = require('./host')
// 封装数据库搜索用户openId检查是否存在的函数
function isExist(openId) {
    return new Promise( (resolve, rejects) => {
        let sql = 'select id from userinfo where open_id=?'
        let ret=query(sql,[openId])
        resolve(ret)
    })
}
// 注册用户
function register(info, openId) {
    return new Promise( (resolve, rejects) => {
        let sql;
        let key;

        sql = "INSERT INTO userinfo ( nickName,avatar,sex,open_id ) VALUES (?,?,?,?);"
        key = [info.nickName, info.avatarUrl, info.gender, openId]
        let ret=query(sql,key)
        resolve(ret)

    })
}
router.post('/', (req, response) => {
    let code = req.body.code
    let info = req.body.info
    let appId = 'wx901b9b086adc8d82'
    let secret = 'ec022d4afd3495d676b8a379be267c5e'
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
    axios({
        method: 'get',
        url
    }).then(async res => {
        const openId = res.data.openid;
        // 查询数据库中是否有该用户,没有就插入,之后返回openid
        let result = await isExist(openId)
        if (!result.length) {
            await register(info, openId)
        }
        response.send({ login: "ok", openId: openId })
    })
})
// 修改磁盘存储规则
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'image/userInfo/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
var upload2 = multer({ storage: storage })
// 修改用户信息
router.post('/info', upload2.single('file'),async (req, res) => {
    // body 包含表单信息
    const info = JSON.parse(req.body.info);
    const avatarUrl = req.file.path.replace(/\\/g, '/').slice(6);
    info.avatarUrl = avatarUrl
    // 获取这些数据存入数据库
    let sql = 'update userinfo set nickName=?,avatar=?,sex=? where open_id=?'
    const ret=await query(sql, [info.nickName, info.avatarUrl, info.gender, info.openId])
    res.send(ret)

})
// 收藏歌曲
router.get('/shoucang', async (req, res) => {
    let id = req.query.id
    let open_id = req.query.openId
    let isCate=req.query.isCate
    let sql = 'INSERT INTO shoucang ( s_id,open_id ,isCate) VALUES (?,?,?); '
    const ret = await query(sql,[id,open_id,isCate])
    res.send(ret)

})
// 找到收藏的具体的一首歌曲
router.get('/oneshoucang',async (req, res) => {
    let id = req.query.id
    let open_id = req.query.openId
    let isCate=req.query.isCate
    let sql='select * from shoucang where s_id=? and open_id=? and isCate=?';
    const ret = await query(sql,[id,open_id,isCate])
    res.send(ret)
})
// 删除收藏的歌曲
router.get('/cancleShoucang',async (req,res)=>{
    let id = req.query.id
    let open_id = req.query.openId
    let isCate=req.query.isCate
    let sql='delete from shoucang where s_id=? and open_id=? and isCate=?';
    const ret = await query(sql,[id,open_id,isCate])
    res.send(ret)

})
// 获取所有收藏的歌曲
router.get('/allShoucang',async (req,res)=>{
    let open_id = req.query.openId
    let page=req.query.page
    let count=7
    let start=(parseInt(page)-1)*count
    let sql=`select s_id,isCate from shoucang where open_id=? limit ${start},${count}`
    const ret = await query(sql,[open_id]);
    const pros = ret.map(ele=>{
        if(ele.isCate==='true'){
            sql='select * from detail where id=?';
        }else{
            sql="select * from zhuanji where id=?"
        }
        return query(sql,[ele.s_id])
    });
    let result = await Promise.all(pros);
    result = result.map(ele=>ele[0])
    res.send({data:result,code:200})
})

module.exports = router